package com.banshuibao.bsb_android.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.banshuibao.bsb_android.Constants;
import com.banshuibao.bsb_android.R;
import com.banshuibao.bsb_android.adapter.MoreLiveAdapter;
import com.banshuibao.bsb_android.http.HttpResponse;
import com.banshuibao.bsb_android.http.HttpUtil;
import com.banshuibao.bsb_android.model.MediaModel;
import com.banshuibao.bsb_android.model.MoreLiveModel;
import com.banshuibao.bsb_android.model.NewSearchResultModel;
import com.banshuibao.bsb_android.model.RequestMoreModel;
import com.banshuibao.bsb_android.pulltolistview.PullToRefreshBase;
import com.banshuibao.bsb_android.pulltolistview.PullToRefreshListView;
import com.banshuibao.bsb_android.util.DialogUtils;
import com.banshuibao.bsb_android.util.IntentManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * Created by wangpan on 2018/3/26.
 */

@SuppressLint("ValidFragment")
public class LiveMoreFragment extends BaseFragment implements PullToRefreshListView.OnRefreshListener2, AdapterView.OnItemClickListener {

    private PullToRefreshListView pullToRefreshListView;
    private ListView listView;
    private String key, title, voideId;
    private MoreLiveAdapter adapter;
    private int startId, endId;
    private boolean isUp;
    private double price;
    private String img;

    public LiveMoreFragment(String key, String title) {
        this.key = key;
        this.title = title;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.search_listview_layout, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        pullToRefreshListView = getView().findViewById(R.id.ptrlv);
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        pullToRefreshListView.loadBar();
        pullToRefreshListView.setOnRefreshListener(this);
        listView = pullToRefreshListView.getRefreshableView();
        listView.setDivider(null);
        adapter = new MoreLiveAdapter(getActivity());
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(this);
        getData();
    }

    public void getData() {
        isUp = false;
        startId = 1;
        endId = startId + 9;
        if (adapter != null) {
            int count = adapter.getCount();
            if (count > 10) {
                endId += count - 10;
            }
        }
        requestNet();
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        getData();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        isUp = true;
        endId = startId + 9;
        requestNet();
    }

    public void requestNet() {
        RequestMoreModel requestMoreModel = new RequestMoreModel();
        requestMoreModel.setSinceId(startId);
        requestMoreModel.setMaxId(endId);
        requestMoreModel.setType("tiny");
        requestMoreModel.setContent(key);
        HttpUtil.doPost(Constants.Url.SEARCH_MORE, requestMoreModel, new HttpResponse(getActivity(), MoreLiveModel.class) {
            @Override
            public void onResult(Object obj) {
                //  String json = (String) obj;
                MoreLiveModel model = (MoreLiveModel) obj;
                List<NewSearchResultModel.DataBean.TinyVideosBean> tinyVideosBeans = model.getData();
                int rows = model.getRows();
                startId += rows;
                if (isUp) {
                    adapter.upData(tinyVideosBeans);
                } else {
                    adapter.downData(tinyVideosBeans);
                }

            }

            @Override
            public void responseEnd() {
                super.responseEnd();
                pullToRefreshListView.onRefreshComplete();
            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (adapter != null) {
            NewSearchResultModel.DataBean.TinyVideosBean videosBean = adapter.getItem(position - 1);
            price = videosBean.getPrice();
            voideId = videosBean.getId();
            img = videosBean.getImage();
            buyMedia(title, price, voideId, videosBean.getImage());
        }
    }

    void buyMedia(final String title, final double price, final String id, final String img) {
        MediaModel.BuyBody buyBody = new MediaModel.BuyBody();
        buyBody.setUuid(id);
        HttpUtil.doPost(Constants.Url.IS_BUY, buyBody, new HttpResponse(getActivity()) {
            @Override
            public void onResult(Object obj) {
                JSONObject jsonObject = null;
                JSONObject jsonObject1 = null;
                try {
                    jsonObject = new JSONObject((String) obj);
                    jsonObject1 = jsonObject.getJSONObject("data");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (jsonObject1 != null) {
                    String type = jsonObject1.optString("type");
                    String vid = jsonObject1.optString("vid");
                    if ("0".equals(type) && !TextUtils.isEmpty(vid)) {
                        IntentManager.goMediaPlayActivity(getActivity(), vid, Constants.Url.VIDEO, id, img);
                    } else {
                        Dialog buyDialog = DialogUtils.payDialog(getActivity(), "您可以支付" + price + "元购买单集或支付365元购买会员卡观看所有视频!", title, String.valueOf(price), id, 4);
                        if (!buyDialog.isShowing())
                            buyDialog.show();
//                        new AlertDialog.Builder(getActivity()).
//                                setMessage("购买365会员可以免费观看所有视频,或者支付" + price + "元购买本集").
//                                setPositiveButton("购买", new DialogInterface.OnClickListener() {
//                                    @Override
//                                    public void onClick(DialogInterface dialogInterface, int i) {
//                                        //IntentManager.goPayResultActivity(getActivity(), data.getTitle(), String.valueOf(data.getPrice()), data.getId(), 4);
//                                        Intent intent = new Intent(getActivity(), PayActivity.class);
//                                        intent.putExtra("flag", 4);
//                                        intent.putExtra("content", title);
//                                        intent.putExtra("price", String.valueOf(price));
//                                        intent.putExtra("uuid", id);
//                                        startActivityForResult(intent, 200);
//                                    }
//                                }).setNegativeButton("取消", null).create().show();
                    }
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 200)
                buyMedia(title, price, voideId, img);
        }
    }
}
